package com.forezp.configclient.rabbitMq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @version V1.0  </br>
 * @ClassName Work </br>
 * @Description TODO  </br>
 * @Author tonywang</br>
 * @DATE 11/23/2018 10:38 AM</br>
 */
public class Work {
    //队列名称
    private final static String QUEUE_NAME = "workqueue";

    public static void main(String[] args) throws IOException, TimeoutException {
        //区分不同工作进程的输出
        int hashCode = Work.class.hashCode();
        //创建连接和频道
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("root");
        factory.setPassword("root");
        factory.setVirtualHost("/");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //声明队列
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        System.out.println(hashCode
                + " [*] Waiting for messages. To exit press CTRL+C");
        //设置最大服务转发消息数量
        int prefetchCount = 1;
        channel.basicQos(prefetchCount);
        //创建队列消费者
        DefaultConsumer consumer =new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                String msg=new String(body,"UTF-8");
                System.out.println("Received message is:"+msg);
                try {
                    doWork(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(hashCode + " [x] Done");
                //发送应答
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        boolean ack = false ; //打开应答机制
        //指定消费队列
        channel.basicConsume(QUEUE_NAME,ack,consumer);
    }
    /**
     * 每个点耗时1s
     * @param task
     * @throws InterruptedException
     */
    private static void doWork(String task) throws InterruptedException
    {
        for (char ch : task.toCharArray())
        {
            if (ch == '.')
                Thread.sleep(1000);
        }
    }
}
